package com.kusej.gitmanger.form;

import com.intellij.icons.AllIcons;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.kusej.gitmanger.utils.FileModifyUtils;
import com.kusej.gitmanger.utils.GitBranchUtils;
import com.kusej.gitmanger.utils.LoadUtils;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import static com.kusej.gitmanger.utils.TimeUtils.dateFormatYYYYmmdd;

/**
 * 创建tag
 */
public class TagCreateDialog extends DialogWrapper {
    private TagCreate tagCreate;
    private JComboBox<String> comboBox;
    private final Project project;

    public TagCreateDialog(@Nullable Project project) {
        super(project, true, IdeModalityType.IDE);
        this.project = project;
        init();
        setTitle("创建tag");
        setSize(500, 400);
    }

    @Override
    protected @Nullable JComponent createCenterPanel() {
        tagCreate = new TagCreate();
        comboBox = tagCreate.getSourceBranch();
        initComboBoxData();
        return tagCreate.getContentPanel();
    }

    @Override
    protected void doOKAction() {
        super.doOKAction();
        LoadUtils.defaultLoading(project, "Create hotfix ...");
        String descText = tagCreate.getBranchDesc().getText();// 分支描述
        try {
            String sourceBranchName = Objects.requireNonNull(tagCreate.getSourceBranch().getSelectedItem(), "基础分支不可为空").toString();// 源分支
            String targetBranchName = tagCreate.getTargetBranch().getText();// 新建的分支名称
            GitBranchUtils.fetch(project.getBasePath(), sourceBranchName);
            GitBranchUtils.createAndPushTag(this.project.getBasePath(), sourceBranchName, targetBranchName, descText);
            Messages.showMessageDialog("Success：Tag创建成功", "Message", AllIcons.Actions.Commit);
        } catch (Exception e) {
            e.printStackTrace();
            Messages.showErrorDialog(e.getMessage(), "ERROR");
        }
        LoadUtils.closeLoading();
    }

    private void initComboBoxData() {
        try {
            System.out.println("TagCreateDialog.initComboBoxData==>" + this.project.getBasePath());
            List<String> newData = GitBranchUtils.getRemoteBranches(this.project.getBasePath());
            DefaultComboBoxModel<String> newModel = new DefaultComboBoxModel<>(newData.toArray(new String[0]));
            comboBox.setModel(newModel); // 更新 JComboBox 的数据
            tagCreate.getTargetBranch().setText("tag-" + dateFormatYYYYmmdd.format(new Date())+".1");
        } catch (Exception e) {
            e.printStackTrace();
            Messages.showErrorDialog(e.getMessage(), "ERROR");
        }
    }

}
